import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
import { getAction } from '@/services/manage'

// 获取下拉字典
export function getSelectDictCode(list) {
  const str = JSON.stringify(list)
  const dictCodes = extractDynamicKeyData(str)
  return [...new Set(dictCodes)]
}

// 根据dictCode数组请求数据
export async function getSelectOptions(dictCodes) {
  let dynamicData = {}
  const queryParam = new Criteria()
  queryParam.addCriterions({ 'dictCode@IN': dictCodes.join() }, OPERATOR.LIKE)// 过滤参数转换为jpa支持格式
  var param = Object.assign({}, { criteria: queryParam.getEncode() })
  const res = await getAction('/sys/dict/tree/page', param)
  if (res.success) {
    res.result.content.forEach(dict => {
      dynamicData[dict.dictCode] = []
      dict.items.forEach(item => {
        dynamicData[dict.dictCode].push({
          label: item.itemText,
          value: item.itemValue
        })
      })
    })
  } else {
    dynamicData = {}
  }
  return dynamicData
}

// 表单设计字段根据${nodeId}标识替换为绑定节点id
export function replaceFormModel(list, nodeId) {
  const str = JSON.stringify(list)
  return JSON.parse(str.replaceAll('${nodeId}', nodeId || ''))
}

// 根据dynamicKey字段匹配字典code
function extractDynamicKeyData(string) {
  var pattern = /"dynamicKey":"([^"]*)"/g
  var matches = string.matchAll(pattern)
  var codes = []
  for (var match of matches) {
    var code = match[1]
    codes.push(code)
  }
  return codes
}

// 获取下拉字典-已废弃
export function getSelectDictCode2(list) {
  let dictCodes = []
  if (list && list.length > 0) {
    list.forEach(item => {
      if (item.type === 'select' && item.options.dynamic) {
        dictCodes.push(item.options.dynamicKey)
      } else if (item.type === 'grid' || item.type === 'tabs') {
        let list = []
        item.columns.forEach(li => {
          list = list.concat(li.list)
        })
        dictCodes = dictCodes.concat(getSelectDictCode(list))
      } else if (item.type === 'table') {
        let tds = []
        item.trs.forEach(tr => {
          tr.tds.forEach(td => {
            tds = tds.concat(td.list)
          })
        })
        dictCodes = dictCodes.concat(getSelectDictCode(tds))
      } else if (item.type === 'card') {
        dictCodes = dictCodes.concat(getSelectDictCode(item.list))
      }
    })
  }
  return dictCodes
}
